import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
  ReloadOutlined,
  LinkOutlined,
  SearchOutlined, UndoOutlined
} from '@ant-design/icons';
import {
  Button,
  message,
  Form,
  Modal,
  Upload,
  UploadProps,
  Row,
  Col,
  Input,
  Popconfirm,
  Select,
  Image,
  Radio,
  TreeSelect,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import '@/assets/css/index.less';
import {
  deletePhotoByPhoId,
  getPhotoListWithoutSpe,
} from '@/services/pictureManager';
import { history, useModel } from 'umi';
import formatDate from '@/utils/formatDate';
import { ProForm } from '@ant-design/pro-components';
import { getPhoCatListWithoutSpe } from '@/services/category';
import {addWhiteList, deleteWhiteList, deleteWhiteListByArr, getWhiteList, updateWhiteList} from "@/services/ipLimit";
import {ModalForm, ProFormText} from "@ant-design/pro-form";


const PicturenManagement: React.FC = () => {
  const [form] = Form.useForm();
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [currentRow, setCurrentRow] = useState<any>();
  const formLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };
  const [selectedRows, setSelectedRows] = useState([]);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="关键字" name="ip">
                <Input placeholder="请输入ip地址" onChange={() => queryData()} />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item label="接口地址" name="addr">
                <Input placeholder="请输入接口地址" onChange={() => queryData()} />
              </Form.Item>
            </Col>
            <Col
              span={4}
              className="basic-search-form-submit-btn"
              style={{ display: 'flex', justifyContent: 'flex-end' }}
            >
              <Button
                onClick={() => {
                  form.resetFields();
                  queryData();
                }}
              >
                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };
  const actionRef = useRef<ActionType>();
  const [approveForm] = Form.useForm();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(40);
  const [dataArray, setDataArray] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [loadingTable, setLoadingTable] = useState(true);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });
  const [batchDel,setBatchDel] = useState(false)

  useEffect(()=>{
    if(selectedRows && selectedRows.length>0){
      setBatchDel(true)
    }else{
      setBatchDel(false)

    }
  },[selectedRows])

  const handleDelete = async (record: any) => {
    try {
      const res = await deleteWhiteList({ id: record.id },{ id: record.id });
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败' + error.response.data.message);
    }
    queryData();
  };

  useEffect(() => {
    queryData(true);
  }, [page, pageSize]);


  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
    setPagination({ ...pagination });
  };
  const queryData = async (pageChanged) => {
    setLoadingTable(true);
    let values = form.getFieldsValue();
    Object.keys(values).map((item) => {
      if (values[item] === 'all') delete values[item];
    });
    let params = {};
    if (!Object.values(values).every((i) => !i) && !pageChanged) {
      //搜索状态，page为1
      params = {
        page: 1,
        pageSize: pageSize,
      };
    } else {
      //搜索状态
      params = {
        page: page,
        pageSize: pageSize,
      };
    }

    const msg = await getWhiteList(params, values);
    setDataArray(msg.data.apiWhiteList);
    let paginationNew = pageChanged
      ? {
        ...pagination,
        total: msg.data.total,
      }
      : {
        ...pagination,
        total: msg.data.total,
        current: 1,
      };
    setPagination(paginationNew);

    setLoadingTable(false);
  };

  const columns: ProColumns[] = [
    {
      title: 'IP地址',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'ip',
    },
    {
      title: '接口',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'addr',
    },
    {
      title: '对接平台',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'name',
    },
    {
      title: '访问次数',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'visitTimes',
    },
    {
      title: '响应时间',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'respTime',
    },
    {
      title: '发布者',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdBy',
    },
    {
      title: '发布时间',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdTime',
    },
    {
      title: '操作',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'id',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRow(record)
            handleModalVisible(true)
          }}
        >
          <Button className={'button'} shape={'round'} type="primary" icon={<EditOutlined />}>
            编辑
          </Button>
        </a>,
        <Popconfirm title={record.sts == 1 ? '确定是否停用?' : '确定是否启用?'}
                    onConfirm={async () => {
                      const success = await updateWhiteList({...record, sts: record.sts == 1 ? 0 : 1})
                      if(success){
                        message.success('编辑成功')
                        queryData()
                      }
                    }} key="update">
          <a style={{ color: record.sts == 1 ? 'red' : 'green' }}>
            <Button className={'buttonMargin'} shape={'round'} icon={record.sts == 1 ? <LinkOutlined /> : <ReloadOutlined />}>
              {record.sts == 1 ? '停用' : '启用'}
            </Button>
          </a>
        </Popconfirm>,

        <Popconfirm title="确定是否删除?" onConfirm={() => handleDelete(record)} key="delete">
          <a style={{ color: 'red' }}>
            <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
              删除
            </Button>
          </a>
        </Popconfirm>,
      ],
    },
  ];


  return (
    <PageContainer>
      {_initSearchForm()}
      <ProTable
        search={false}
        loading={loadingTable}
        actionRef={actionRef}
        rowKey="id"
        tableStyle={{ textAlign: 'center' }}
        options={false}
        pagination={pagination}
        dataSource={dataArray}
        onChange={handleTableChange}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true)
            }}
          >
            <PlusOutlined />
            新增白名单
          </Button>,

           <Popconfirm
              disabled={!batchDel}
              title="确定是否批量删除?"
              onConfirm={async () => {
                const success = await deleteWhiteListByArr(selectedRows.map(i => i.id))
                if (success) {
                  message.success('操作成功')
                  queryData()
                }
                if (actionRef.current) {
                  actionRef.current.reload();
                  actionRef.current.clearSelected();
                }
              }}
              key="delete"
            >
              <Button disabled={!batchDel} type="primary" key="primay" danger>
                <DeleteOutlined />
                批量删除
              </Button>
            </Popconfirm>


        ]}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      ></ProTable>
      <ModalForm
        title="新增白名单"
        width="600px"
        layout={'horizontal'}
        {...formLayout}
        visible={createModalVisible}
        onVisibleChange={bool=>{
          handleModalVisible(bool)
          if(!bool) setCurrentRow({})
        }}
        modalProps={{ destroyOnClose: true }}
        onFinish={async (value) => {
          if(currentRow && currentRow.id){
            const success = await updateWhiteList({...value,id:currentRow.id,'addr':'/api/v1/topic/getPlcTopicList',sts:1});
            if (success) {
              message.success('编辑成功');
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }else{
            const success = await addWhiteList({...value,'addr':'/api/v1/topic/getPlcTopicList',sts:1});
            if (success) {
              message.success('新增成功');
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }
          queryData()
        }}
      >
        <ProFormText
          initialValue={currentRow?.ip}
          rules={[
            {
              required: true,
              message: 'IP地址必填！',
            },
            {
              validator:(rule,val,cb)=>{
                console.log(val);
                const test = /^((?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d))$/
                if (test.test(val)) {
                  return Promise.resolve()
                }else{
                  return Promise.reject(new Error("请输入正确的IP地址"))
                }
              }
            }
          ]}
          width="md"
          name="ip"
          placeholder="请输入IP地址"
          label="IP地址"
        />

        <ProFormText
          initialValue={currentRow?.name}
          rules={[
            {
              required: true,
              message: 'IP地址必填！',
            }
          ]}
          width="md"
          name="name"
          placeholder="请输入对接平台"
          label="对接平台"
        />
      </ModalForm>

    </PageContainer>
  );
};
export default PicturenManagement;
